/**
*    This file is part of Basic Service.
*
*    Basic Service is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    Basic Service is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with Basic Service (See GPL.txt).  If not, see <http://www.gnu.org/licenses/>.
*    
* 	If needed the author is Amir Zucker and can be reached at amirzucker1@gmail.com or amirzucker.wordpress.com
*/
package com.basicservice.service;

import java.util.ArrayList;
import java.util.List;

import org.owasp.esapi.ESAPI;
import org.owasp.esapi.errors.EncryptionException;
import org.owasp.esapi.errors.IntrusionException;
import org.owasp.esapi.errors.ValidationException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import com.basicservice.domain.User;

/**
 * A service used to save and retrieve email confirmation keys for users
 */

@Service
public class SecurityService {
	public String hash(String value, String salt) throws EncryptionException {
		return ESAPI.encryptor().hash(value, salt);
	}
	
	public String getValidInput(String context, String input, 
			String type, int maxLength, 
			boolean allowNull) throws ValidationException, IntrusionException {
		return ESAPI.validator().getValidInput(context, input,
				type, maxLength, allowNull);
	}

	public void signInUserToSecurityContext(User user) {
		String[] roles = user.getRoles();
		List<GrantedAuthority> authorities = null;
		if (roles != null && roles.length > 0) {
			authorities = new ArrayList<GrantedAuthority>(roles.length);
			for (int i = 0; i < roles.length; i++) {
				authorities.add(new SimpleGrantedAuthority(roles[i]));
			}
		}
		SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user.getId(), null, authorities));	
	}

	public void signoutUser() {
		SecurityContextHolder.getContext().setAuthentication(null);
	}
}
